package com.shark.open.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.shark.open.config.ReqContext;
import com.shark.utils.exception.XException;
import com.shark.utils.security.MD5Util;
import com.shark.utils.tools.JsonTool;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.Optional;
import java.util.TreeMap;

@Slf4j
public class SignUtils {
    public static void checkSign(Object param) {

        ReqContext.AccessContext context = ReqContext.getContext();
        String jsonStr = JSONUtil.toJsonStr(param);
        log.error("接口请求 param={}",jsonStr);
        TreeMap paramMap = Optional.ofNullable(JsonTool.toObject(jsonStr, TreeMap.class)).orElse(new TreeMap());
        paramMap.put("accessKey", context.getAccessKey());
        paramMap.put("timespan", context.getTimespan());
        StringBuilder sb = new StringBuilder();
        paramMap.forEach((k, v) -> {
            if (Objects.nonNull(v)) {
                sb.append(StrUtil.format("&{}={}", k, v));
            }
        });
        String paramStr=sb.toString().substring(1);
        String sign = MD5Util.crypt(paramStr);
        if (!sign.equalsIgnoreCase(context.getSign())) {
            log.error("接口请求 accessId={}, accessKey={}, timespan={}, sign={}, param={}",
                    context.getAccessId(), context.getAccessKey(), context.getTimespan(), context.getSign(), paramStr);
            log.error("服务器签名={}", sign);
            throw new XException("签名错误");
        }
    }
}
